﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Web;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace ZDic
{
    class Program
    {
        [STAThread]     //如果要在控制台程序中使用剪贴板则要加上该标记
        static void Main(string[] args)
        {
            String key_words=null;
            if (args.Length == 0)
            {
                //如果没有带额外参数，则从剪贴板中获取关键词
                IDataObject id = Clipboard.GetDataObject();
                if (id.GetDataPresent(DataFormats.Text))
                {
                    key_words = (String)id.GetData(DataFormats.Text);
                }
                else
                    return;
            }
            else
                key_words = args[0];        //默认关键词为第一个参数
            key_words=key_words.Trim();     //去掉两边空白符
            Console.WriteLine("\t{0}:\n", key_words);
            if (key_words.Length == 0) return;
            //使用IsLetter()函数会将汉字也判断为字母
            int mode = char.IsLower(key_words[0]) | char.IsUpper(key_words[0]) ? 1 : 0;
            ZDictionary.TranslateWords(key_words, mode);
        }
    }
    class ZDictionary
    {
        private static Regex regex_content = new Regex("<div class=\"content\">(.*?)</div>", RegexOptions.Compiled | RegexOptions.Singleline);
        private static Regex regex_c2e2 = new Regex("[1-9].&nbsp;(.*?)<br/>", RegexOptions.Compiled | RegexOptions.Singleline);
        private static Regex regex_e2c2 = new Regex("[.](.*?)<br/>", RegexOptions.Compiled | RegexOptions.Singleline);
        private static Regex regex_web = new Regex("<div class=\"content\" id=\"listtrans\">(.*?)</div>",
                                                    RegexOptions.Compiled | RegexOptions.Singleline);   //有道网络释义正则
        private static Regex regex_web2 = new Regex("<li>(.*?)</li>", RegexOptions.Compiled | RegexOptions.Singleline);
        public static String TranslateWords(String s,int mode)
        {
            String key_words = "http://dict.youdao.com/m/search?keyfrom=dict.mindex&vendor=&q=" + ZDictionary.UrlEncode(s);
            HttpWebRequest request;
            HttpWebResponse response;
            try
            {
                request = (HttpWebRequest)WebRequest.Create(key_words);
                request.UserAgent = "Nokia5320";
                response=(HttpWebResponse)request.GetResponse();
            }
            catch (Exception)
            {
                Console.WriteLine("\n\t无法连接服务器请检查网络是否通畅\n");
                return null;
            }
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            String html=reader.ReadToEnd();
            Regex regex_words = mode == 0 ? regex_c2e2 : regex_e2c2;
            Match match_content = regex_content.Match(html);        //匹配翻译结果
            String words = match_content.Groups[0].ToString();   //取出内容
            MatchCollection mc = regex_words.Matches(words);
            foreach (Match m in mc)
            {
                //取出每个单词
                Console.Write("\t");
                String result = m.Groups[1].ToString().Trim().Replace('\n',' ');
                Int32 space_begin=result.IndexOf(' ');
                Int32 space_end=result.LastIndexOf(' ');
                if(space_begin>0&&space_end>space_begin)
                    result = result.Remove(space_begin, space_end - space_begin);
                Console.WriteLine(result);
            }
            match_content = regex_web.Match(html);      //匹配网络释义结果
            if (match_content != null)
            {
                Console.WriteLine("\n");
                words = match_content.Groups[1].ToString();
                mc = regex_web2.Matches(words);
                if (mc.Count == 0)
                {
                    Console.WriteLine("\t\t没有找到\"{0}\"翻译结果", s);
                    return null;
                }
                foreach (Match m in mc)
                {
                    Console.Write("\t");
                    Console.WriteLine(m.Groups[1].ToString().Trim());
                }
                Console.WriteLine("\n");
                
            }
            return null;
        }
        private static string UrlEncode(string str)
        {
            StringBuilder sb = new StringBuilder();
            byte[] byStr = System.Text.Encoding.UTF8.GetBytes(str); //默认是System.Text.Encoding.Default.GetBytes(str)
            for (int i = 0; i < byStr.Length; i++)
            {
                sb.Append(@"%" + Convert.ToString(byStr[i], 16));
            }

            return (sb.ToString());
        }
    }
}
